#!/bin/bash

APP_URL="http://127.0.0.1:5000/dezhou"

echo "=========================================="
echo "Flask大数据可视化项目 - 启动脚本"
echo "=========================================="
echo

echo "检查虚拟环境..."
if [ ! -f "venv/bin/activate" ]; then
    echo "错误: 虚拟环境不存在，请先运行 ./install.sh 安装依赖"
    exit 1
fi

echo "激活虚拟环境..."
source venv/bin/activate

echo
echo "启动Flask应用..."
echo "应用将在 $APP_URL 启动"
echo "按 Ctrl+C 停止应用"
echo

# 在后台启动Flask应用
python app.py &
FLASK_PID=$!

echo "等待Flask应用启动..."
sleep 5

# 检查应用是否启动成功
echo "检查应用状态..."
for i in {1..10}; do
    if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:5000/dezhou | grep -q "200\|404"; then
        echo "Flask应用已启动成功！"
        break
    fi
    echo "等待中... ($i/10)"
    sleep 2
done

echo "打开浏览器..."
# 检测操作系统并打开浏览器
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    open $APP_URL
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # Linux
    if command -v xdg-open > /dev/null; then
        xdg-open $APP_URL
    elif command -v firefox > /dev/null; then
        firefox $APP_URL &
    elif command -v google-chrome > /dev/null; then
        google-chrome $APP_URL &
    elif command -v chromium-browser > /dev/null; then
        chromium-browser $APP_URL &
    else
        echo "未找到可用的浏览器，请手动打开 $APP_URL"
    fi
else
    echo "不支持的操作系统，请手动打开 $APP_URL"
fi

# 等待用户中断
echo "按 Ctrl+C 停止应用"
wait $FLASK_PID
